package com.ctrip.corp.obt.shard.sql.mybatis.interceptor;

import com.ctrip.corp.obt.generic.utils.StringPool;
import com.ctrip.corp.obt.shard.configuration.DataShardProperties;
import com.ctrip.corp.obt.shard.holder.InnerPluginIgnoreHolder;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.inner.InnerPlugin;
import com.ctrip.corp.obt.shard.utils.ClassUtils;
import com.ctrip.corp.obt.shard.utils.PropertiesWrapper;
import lombok.Setter;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.InitializingBean;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 封装Interceptor所有阶段的执行状态
 * Executor：代表执行器，由它调度StatementHandler、ParameterHandler、ResultSetHandler等来执行对应的SQL，其中StatementHandler是最重要的。
 * StatementHandler：作用是使用数据库的Statement（PreparedStatement）执行操作，它是四大对象的核心，起到承上启下的作用，许多重要的插件都是通过拦截它来实现的。
 * ParameterHandler：是用来处理SQL参数的。
 * ResultSetHandler：是进行数据集（ResultSet）的封装返回处理的，它非常的复杂，好在不常用。
 * @author marco.zheng
 * @since 2022-03-15
 */
@SuppressWarnings({"rawtypes"})
@Intercepts(
    {
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
        @Signature(type = StatementHandler.class, method = "getBoundSql", args = {}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
    }
)
public class InnerPluginsInterceptor implements Interceptor, InitializingBean {

    @Setter
    private List<InnerPlugin> interceptors = new ArrayList<>();

    public InnerPluginsInterceptor() {

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!DataShardProperties.isEnabledInnerPluginsInterceptor()) {
            return invocation.proceed();
        }
        Object target = invocation.getTarget();
        Object[] args = invocation.getArgs();
        if (target instanceof Executor) {
            final Executor executor = (Executor) target;
            Object parameter = args[1];
            boolean isUpdate = args.length == 2;
            MappedStatement ms = (MappedStatement) args[0];
            // 此处满足条件则忽略所有插件执行逻辑
            if (InnerPluginIgnoreHolder.willIgnoreAll(ms.getId())) {
                return invocation.proceed();
            }
            if (!isUpdate && ms.getSqlCommandType() == SqlCommandType.SELECT) {
                return selectProcess(args, executor, parameter, ms);
            } else if (isUpdate) {
                return updateProcess(invocation, executor, parameter, ms);
            }
        } else {
            final StatementHandler sh = (StatementHandler) target;
            // 目前只有StatementHandler.getBoundSql方法args才为null
            if (null == args) {
                getBoundSqlProcess(sh);
            } else {
                prepareProcess(args, sh);
            }
        }
        return invocation.proceed();
    }

    /**
     * prepare
     * @param args Invocation args
     * @param sh {@link StatementHandler}
     */
    private void prepareProcess(Object[] args, StatementHandler sh) {
        Connection connections = (Connection) args[0];
        Integer transactionTimeout = (Integer) args[1];
        for (InnerPlugin innerPlugin : interceptors) {
            innerPlugin.beforePrepare(sh, connections, transactionTimeout);
        }
    }

    /**
     * getBoundSql
     * @param sh {@link StatementHandler}
     */
    private void getBoundSqlProcess(StatementHandler sh) {
        for (InnerPlugin innerPlugin : interceptors) {
            innerPlugin.beforeGetBoundSql(sh);
        }
    }

    /**
     * update
     * @param invocation {@link Invocation}
     * @param executor {@link Executor}
     * @param parameter parameter
     * @param ms MappedStatement
     * @return
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private Object updateProcess(Invocation invocation, Executor executor, Object parameter, MappedStatement ms) throws SQLException, InvocationTargetException, IllegalAccessException {
        for (InnerPlugin update : interceptors) {
            if (!update.whetherDoUpdate(executor, ms, parameter)) {
                return -1;
            }
            update.beforeUpdate(executor, ms, parameter);
        }
        return invocation.proceed();
    }

    /**
     * select
     * @param args Invocation args
     * @param executor {@link Executor}
     * @param parameter parameter
     * @param ms MappedStatement
     * @return
     * @throws SQLException
     */
    private Object selectProcess(Object[] args, Executor executor, Object parameter, MappedStatement ms) throws SQLException {
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        BoundSql boundSql;
        if (args.length == 4) {
            boundSql = ms.getBoundSql(parameter);
        } else {
            // 几乎不可能走进这里面,除非使用Executor的代理对象调用query[args[6]]
            boundSql = (BoundSql) args[5];
        }
        for (InnerPlugin query : interceptors) {
            if (query.skipPluginQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql)) {
                continue;
            }
            if (!query.whetherDoQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql)) {
                return Collections.emptyList();
            }
            query.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        }
        CacheKey cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
        return executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor || target instanceof StatementHandler) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    public void addInnerInterceptor(InnerPlugin innerPlugin) {
        this.interceptors.add(innerPlugin);
    }

    public List<InnerPlugin> getInterceptors() {
        return Collections.unmodifiableList(interceptors);
    }

    /**
     * mybatis-config.xml
     * -------------------------------------------------------------------------------------------------------------
     * <plugins>
     *   <plugin interceptor="com.ctrip.corp.obt.shard.sql.mybatis.interceptor.InnerPluginsInterceptor">
     *     <property name="@page" value="com.ctrip.corp.obt.shard.sql.mybatis.interceptor.inner.PaginationInnerPlugin"/>
     *     <property name="page:dbType" value="mysql"/>
     *     <property name="page:overflow" value="true"/>
     *     <property name="page:dialect" value="com.ctrip.corp.obt.shard.sql.mybatis.interceptor.dialect.MysqlDialect"/>
     *     <property name="page:maxLimit" value="1000"/>
     *     <property name="page:optimizeJoin" value="true"/>
     *     <property name="@table" value="com.ctrip.corp.obt.shard.sql.mybatis.interceptor.inner.TableRerouteInnerPlugin"/>
     *     <property name="table:tableRerouteHandler" value="com.ctrip.corp.obt.shard.sql.parser.table.DefaultTableRerouteHandler"/>
     *     <property name="@tenant" value="com.ctrip.corp.obt.shard.sql.mybatis.interceptor.inner.TenantInnerPlugin"/>
     *     <property name="tenant:tenantHandler" value="com.ctrip.corp.obt.shard.sql.parser.tenant.DefaultTenantHandler"/>
     *   </plugin>
     * </plugins>
     * -------------------------------------------------------------------------------------------------------------
     */
    @Override
    public void setProperties(Properties properties) {
        PropertiesWrapper wrapper = PropertiesWrapper.newInstance(properties);
        Map<String, Properties> group = wrapper.group(StringPool.AT);
        group.forEach((k, v) -> {
            InnerPlugin plugin = ClassUtils.newInstance(k);
            plugin.setProperties(v);
            addInnerInterceptor(plugin);
        });
        pluginSorted();
    }

    @Override
    public void afterPropertiesSet() {
        pluginSorted();
    }

    private void pluginSorted() {
        this.interceptors.sort(Comparator.comparingInt(InnerPlugin::order));
    }

}
